package com.erp.shop.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.erp.shop.domain.ErpSellerStoreCookie;
import com.erp.shop.mapper.*;
import com.ruoyi.ae.api.RemoteAeActivityService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.oldController.BaseController;
import com.ruoyi.gather.api.RemoteSellerStoreProductService;
import com.ruoyi.shop.api.domain.ErpSellerStorePromotionActivity;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 店铺可用类目品牌
 *
 * @author erp
 * @date 2023-07-21
 */
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/seller/test")
public class StoreTestController extends BaseController {
    @Resource
    RemoteSellerStoreProductService remoteSellerStoreProductService;
    @Resource
    RemoteAeActivityService remoteAeActivityService;
    private final ErpSellerStorePromotionActivityMapper baseMapper;
    private final ErpSellerStoreCookieMapper erpSellerStoreCookieMapper;
    private final ErpSellerStoreEmpowerMapper erpSellerStoreEmpowerMapper;
    private final ErpSellerStorePriceTemplateMapper erpSellerStorePriceTemplateMapper;
    private final ErpSellerStorePromotionActivityProductMapper erpSellerStorePromotionActivityProductMapper;

    @GetMapping("/sellerTest")
    public R<Object> processingProjectGroupAndDiscount(String storeId ,String productDiscountName) {
//        Long storeId = templateInfo.getStoreId();
//        ErpSellerStoreEmpower store = erpSellerStoreEmpowerMapper.selectById(storeId);
//        ErpSellerStorePriceTemplate template = erpSellerStorePriceTemplateMapper.selectById(templateInfo.getTemplateId());
//        if (Objects.isNull(template)) {
//            return R.fail("定价模版不存在");
//        }
//        //1、商品折扣
//        //2、判断是否是默认
//        //设置活动名
//        String productDiscountName = null;
//        if (Objects.isNull(templateInfo.getProductDiscountId())) {
//            Integer isProductDiscount = templateInfo.getIsProductDiscount();
//            if (isProductDiscount == 0) {
//                //默认
//                productDiscountName = template.getDiscount().setScale(0, BigDecimal.ROUND_DOWN).toString();
//            } else {
//                productDiscountName = templateInfo.getProductDiscount();
//            }
//            //同步活动
//            remoteAeActivityService.selectStoreOngoingPromotions("1", storeId.toString());
//            //查询这个店铺下的这个活动是否存在，不存在则创建，存在则返回id
//            ErpSellerStorePromotionActivity activitySel = baseMapper.selectOne(
//                    new LambdaQueryWrapper<ErpSellerStorePromotionActivity>()
//                            .eq(ErpSellerStorePromotionActivity::getStoreId, storeId)
//                            .eq(ErpSellerStorePromotionActivity::getPromotionName, productDiscountName)
//                            .in(ErpSellerStorePromotionActivity::getStatus, "Ongoing", "NotStarted")
//            );
//            LocalDateTime now = LocalDateTime.now();
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            // 格式化当前时间
//            String nowFormatted = now.format(formatter);
//            LocalDateTime parse = LocalDateTime.parse(nowFormatted, formatter);
////            LocalDateTime oneDayLater = parse.plusDays(-2);
//            LocalDateTime zeroHourOld = parse.plusDays(-1).withHour(0).withMinute(0).withSecond(0).withNano(0);
//            LocalDateTime zeroHour = parse.plusHours(-16);
//
//            //昨天的零点
//            System.out.println(zeroHour);
//
//            if (Objects.isNull(activitySel)) {
//                //创建活动
//                ErpSellerStorePromotionActivity activity = new ErpSellerStorePromotionActivity();
//                activity.setUserId(store.getUserId());
//                activity.setStoreId(storeId);
//                activity.setPromotionName(productDiscountName);
//
//                //开始时间为当前时间-1天
//                activity.setStartTime(zeroHour.format(formatter).toString());
//                // 原始日期时间
////                String startTime = zeroHour.format(formatter);
//                LocalDateTime originalDateTime = LocalDateTime.parse(nowFormatted, formatter);
////                LocalDateTime originalDateTime = LocalDateTime.parse(nowDate);
//                // 计算三个月后的日期时间
//                LocalDateTime oneMonthLater = originalDateTime.plus(3, ChronoUnit.MONTHS);
//                activity.setEndTime(oneMonthLater.format(formatter).toString());
//
//                activity.setErpStatus("0");
//                activity.setHasPromo("false");
////                erpSellerStorePromotionActivityMapper.insert(activity);
////                调用接口，上传至平台 //TODO 爬虫相关，暂不执行
//                R<Object> activityToAe = createActivityByPython(activity);
//                if (activityToAe.getCode() == 200) {
//                    //创建成功，拿到对应值
//                    //同步活动
//                    remoteAeActivityService.selectStoreOngoingPromotions("1", storeId.toString());
//                } else {
//                    activity.setStartTime(zeroHourOld.format(formatter).toString());
//                    activityToAe = createActivityByPython(activity);
//                    if (activityToAe.getCode() == 200) {
//                        remoteAeActivityService.selectStoreOngoingPromotions("1", storeId.toString());
//                    }else {
//                        return R.fail("活动创建失败");
//                    }
//                }
//            }
            //保存活动id
            ErpSellerStorePromotionActivity activityNew = baseMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerStorePromotionActivity>()
                            .eq(ErpSellerStorePromotionActivity::getStoreId, storeId)
                            .eq(ErpSellerStorePromotionActivity::getPromotionName, productDiscountName)
                            .in(ErpSellerStorePromotionActivity::getStatus, "Ongoing", "NotStarted")
            );
            return R.ok();
//            templateInfo.setProductDiscountId(Long.valueOf(activityNew.getPromotionId()));
//            templateInfo.setProductDiscount(productDiscountName);
//        }
//
//        return R.ok(templateInfo);
    }

    public R<Object> createActivityByPython(ErpSellerStorePromotionActivity activity) {
//        ErpSellerStorePromotionActivity activity = erpSellerStorePromotionActivityMapper.selectById(activityId);
//        if (ObjectUtils.isNull(activity)){
//            return R.fail("活动不存在");
//        }

        //获取店铺
        ErpSellerStoreCookie cookie = erpSellerStoreCookieMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerStoreCookie>().eq(ErpSellerStoreCookie::getStoreId,activity.getStoreId())
        );
        if (ObjectUtils.isNull(cookie)){
            return R.fail("获取cookie失败");
        }
        JSONObject object = new JSONObject();
        object.put("cookie_str",cookie.getCookie());
        //开始时间转时间戳
        String startTime = activity.getStartTime();
        String endTime = activity.getEndTime();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化当前时间


        LocalDateTime startTimeDT = LocalDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime endTimeDT = LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        // 将 LocalDateTime 对象转换为 Instant 对象，该对象表示一个确切的时间点
//        Instant endTimeIT = endTimeDT.atZone(ZoneId.systemDefault()).toInstant();
//        Instant startTimeIT = startTimeDT.atZone(ZoneId.systemDefault()).toInstant();
//        long endTimestamp = endTimeIT.toEpochMilli();
//        long startTimestamp = startTimeIT.toEpochMilli();
        Long endTimestamp = endTimeDT.toEpochSecond(ZoneOffset.UTC);
        Long startTimestamp = startTimeDT.toEpochSecond(ZoneOffset.UTC);

        String endStr = endTimestamp.toString() + "000";
        String startStr = startTimestamp.toString() + "000";

        object.put("activityName",activity.getPromotionName());
        object.put("activityStartTime",startStr);
        object.put("activityEndTime",endStr);


        String body = getReturnBody(object.toJSONString());

        System.out.println(body);
        JSONObject bodyJson = JSONObject.parseObject(body);
        Integer code = bodyJson.getInteger("code");
        if (code != 200) {
            return R.ok("失败");
        }else {
            return R.ok("设置成功");
        }
    }

    private String getReturnBody(String data) {
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost("http://47.94.131.193:8000/activity/create");
        post.setHeader("Content-Type", "application/json;charset=utf-8");
        post.setHeader("Accept", "application/json");
        post.setHeader("Content-Encoding", "gzip");
        post.setEntity(new StringEntity(data, StandardCharsets.UTF_8));
        HttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(post);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        HttpEntity response = httpResponse.getEntity();
        try {
            return EntityUtils.toString(response,StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
